package com.lhy.ltss.service;

import com.lhy.ltss.entity.Book;
import com.lhy.ltss.exception.BookSearchException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 查询书籍
 * @author: 李汇远
 */
@Service
public class BookService {

    // 图书馆检索系统的url
    private final String libraryUrl = "http://210.42.38.33/searchresult.aspx?";

    private Connection connection = Jsoup.connect(libraryUrl);

    private final String DEFAULT_KEY = "anywords=c";

    public Map search(HashMap<String, String> data) {
        try {
            String urlParam = toURLParam(data);
            Connection connection = Jsoup.connect(libraryUrl + urlParam);
            return resolveHtml(connection.get());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BookSearchException("图书检索失败，请稍后再试！");
        }
    }

    // 将键值对参数转换成字符串，并进行GBK编码
    private String toURLParam(HashMap<String,String> map) throws UnsupportedEncodingException {
        StringBuilder builder = new StringBuilder(map.size() == 0 ? DEFAULT_KEY : "");
        // 对参数做 GBK 编码
        for (Map.Entry<String,String> entry: map.entrySet()){
            builder.append('&');
            builder.append(entry.getKey());
            builder.append('=');
            builder.append(URLEncoder.encode(entry.getValue().trim(),"GBK"));
        }
        return builder.toString();
    }

    private Map resolveHtml(Document document) {
        Map<String, Object> res = new HashMap<>();
        Elements tableTrs = document.select("table.tb>tbody>tr");
        // 解析每行数据，采用多线程并发方式
        List<Book> rows = tableTrs.parallelStream().map(item -> {
            Elements tds = item.getElementsByTag("td");
            Book book = new Book();
            book.setBook_name(tds.get(1).selectFirst("span>a").html());
            book.setBook_editor(tds.get(2).html());
            book.setBook_publish(tds.get(3).html());
            book.setBook_index(tds.get(5).html());
            book.setNum(Integer.parseInt(tds.get(7).html()));
            return book;
        }).collect(Collectors.toList());
        res.put("rows", rows);
        if (rows.size() == 0) {
            res.put("page", 1);
            res.put("totalPage", 1);
        } else {
            res.put("page", document.selectFirst("span#ctl00_ContentPlaceHolder1_dplblfl2").html());
            res.put("totalPage", document.selectFirst("span#ctl00_ContentPlaceHolder1_gplblfl2").html());
        }
        return res;
    }
}
